﻿/*======================================*\
* Author: Vincent
* LastModifyUser: Vincent
* Description:  
* CreateTime： 2012-05
* Remark:  
\*======================================*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using AppCode.DbDTO;
using System.ComponentModel;
using System.Threading;

namespace AppCode.Domain.Services
{
    /// <summary>
    /// 数据信息初始化
    /// <remarks>
    /// 表字段信息加载
    /// </remarks>
    /// </summary>
    public partial class DbInfoInit
    {

        private int _handlerCount = 0;
        /// <summary>
        /// 加载数据库相关信息
        /// </summary>
        private void ReadDbTableInfo(string[] whereTableName)
        {
            if (DbInfos != null)
            {
                int counts = whereTableName.Length;
                _handlerCount += counts;
                if (counts < 1)
                    return;
                string sqlInStr = string.Join(",", whereTableName);
                ReportTaskInfoToTextEvent(this, new TaskInfoEventArgs() { msg = string.Format("正在处理数据表字段相关信息,剩余[{0}]条\r\n", _currentHaveTables.Count) });

                DataSet ds = new DataSet();
                ds = _db.ExecuteDataSet(_db.GetSqlStringCommond(string.Format(_dbInfoSql, sqlInStr,"")));
                List<TableInfo> items = EntityMapper.ToEntity<TableInfo>(ds.Tables[0]);
                if (items == null || items.Count < 1)
                    throw new Exception("加载数据库相关信息失败！");
                if (DbInfos.DbTableInfo == null)
                    DbInfos.DbTableInfo = new List<TableInfo>();
                foreach (var item in items)
                {
                    DbInfos.DbTableInfo.Add(item);
                }

                ReportTaskInfoToTextEvent(this, new TaskInfoEventArgs() { msg = string.Format("已处理 [{0}]条\r\n", counts) });
                if (_handlerCount == _needHandlerCount)
                {
                    ReportTaskInfoToTextEvent(this, new TaskInfoEventArgs() { msg = "<==表字段信息初始化完成，开始生成代码文件==>", statecode=1 });
                    BeginCreateCodeFile(this, new EventArgs());  //开始生成代码
                }
            }

        }

        /// <summary>
        /// 当前存在需处理的表信息
        /// </summary>
        private List<string> _currentHaveTables = null;
        
        /// <summary>
        /// 默认每次处理10条
        /// </summary>
        private int _excuteCount = 10;

        private  int _needHandlerCount = 0;

        /// <summary>
        /// lock
        /// </summary>
        private static object lockObj = new object();
        /// <summary>
        /// 读取表字段信息
        /// </summary>
        /// <param name="tableNames">检索的表</param>
        /// <param name="excuteCount">每次检索条数</param>
        public void OnReadTableColumnInfo(List<string> tableNames, int excuteCount)
        {
            //每次只检索指定条数，因为读取DB这些信息很慢，尤其是数据表多的时候
            if (tableNames != null && tableNames.Count > 0)
            {
                //DbInfos.DbTablesNeedHandler = null;
                DbInfos.DbTableInfo = null; //先清空上次的数据

                _handlerCount = 0;
                _needHandlerCount = tableNames.Count;
                _currentHaveTables = tableNames;
                DbInfos.DbTablesNeedHandler = new List<string>();
                foreach (var m in tableNames)
                {
                    DbInfos.DbTablesNeedHandler.Add(m);
                }
                _excuteCount = excuteCount;

                //初始化任务执行
                _bgWorkReadTbInfo.RunWorkerAsync();
            }
        }

        /// <summary>
        /// 停止读取表字段信息
        /// </summary>
        public void OffReadTableColumnInfo()
        {
            ReportTaskInfoToTextEvent(this, new TaskInfoEventArgs() { msg = "警告:请求中止执行...\r\n" });
            if (_bgWorkReadTbInfo.IsBusy)
                _bgWorkReadTbInfo.CancelAsync();
            ReportTaskInfoToTextEvent(this, new TaskInfoEventArgs() { msg = "已中止执行...\r\n" });
        }

        #region 工作线程事件
        /// <summary>
        /// 任务执行完成时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bgWorkReadTbInfo_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_currentHaveTables != null && _currentHaveTables.Count>0)
            {
                lock (lockObj)
                {
                    while (!_bgWorkReadTbInfo.IsBusy)
                        _bgWorkReadTbInfo.RunWorkerAsync();//循环执行任务直到完成
                }
            }
        }

        /// <summary>
        /// 报告读取进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bgWorkReadTbInfo_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
         //   throw new NotImplementedException();
        }

        /// <summary>
        /// 执行读取表字段信息的线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void bgWorkReadTbInfo_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_currentHaveTables != null && _currentHaveTables.Count > 0)
            {
                List<string> tmpTables = new List<string>();
                int run = 1;
                for (int i = (_currentHaveTables.Count-1); i >= 0; i--)
                {
                    tmpTables.Add(string.Format("'{0}'",_currentHaveTables[i]));
                    _currentHaveTables.RemoveAt(i);  //移除使用过的元素
                    if (run >= _excuteCount)
                        break;
                    run++;
                }
                if (tmpTables.Count > 0)
                {
                    ReadDbTableInfo(tmpTables.ToArray());
                }
            }
        }
        #endregion
    }
}
